<template>
  <div>
    
    <form v-show="!timing && !timeUp" @submit.prevent="confirmTiming">
      <h3>请选择时间</h3>
      <label>时：</label>
      <input type="number" v-model.number="hours" placeholder="小时" min="0" max="23" required>
      <label>分：</label>
      <input type="number" v-model.number="minutes" placeholder="分钟" min="0" max="59" required>
      <label>秒：</label>
      <input type="number" v-model.number="seconds" placeholder="秒钟" min="0" max="59" required>
      <el-button @click="sendStayFocedMessage" type="primary">确定</el-button>
    </form>

    <div v-show="timing">
      <h3>剩余时间：</h3>
      <div class="countdown-animation" :class="{ 'animation-active': storedTimer > 0 }">
        <div class="digit">{{ formattedHours }}</div>
        <div class="digit">{{ formattedMinutes }}</div>
        <div class="digit">{{ formattedSeconds }}</div>
      </div>
    </div>

    <div v-show="timeUp">
      <h3>倒计时已结束</h3>
      <el-button @click="resetTiming">重新设定</el-button>
    </div>
 
  </div>
</template>

<script>
import { sendToBackground } from "@plasmohq/messaging";
import { Storage } from "@plasmohq/storage";

const storage = new Storage();

export default {
  data() {
    return {
      hours: 0,
      minutes: 0,
      seconds: 0,
      timing: false,
      timeUp: false,
      storedTimer: 0,
    };
  },
  computed: {
    formattedHours() {
      return Math.floor(this.storedTimer / 3600).toString().padStart(2, '0');
    },
    formattedMinutes() {
      return Math.floor((this.storedTimer % 3600) / 60).toString().padStart(2, '0');
    },
    formattedSeconds() {
      return (this.storedTimer % 60).toString().padStart(2, '0');
    },
    timestamp() {
      return new Date().getTime();
    }
  },
  mounted() {
    this.getRemainingTime();
  },
  methods: {
    async getRemainingTime() {
      await storage.get("storedTimer").then((timer) => {

        // 将变量 t 转换为字符串类型
        timer=String(timer)

        // split('_') 函数将字符串基于下划线分隔，并返回一个数组，数组中的元素是拆分后的子字符串
        // 将拆分后的结果赋值给变量 number_split
        let number_split=timer.split('_')

        if (number_split.length==2 && number_split[0]!='0') {

          // popup重启，恢复倒计时
          // 如果有数据存在且不为0，则会恢复之前的倒计时，并显示倒计时界面
          this.storedTimer = parseInt(number_split[0]);
          this.timing = true;
          this.countdown(this.storedTimer);

        } else if(number_split.length==1 && number_split[0]=='0') {

          // 第一次启动，等待用户输入
          // 如果没有数据存在且数据为0，则显示选择时间的界面
          this.timeUp=false
          this.timing=false
        } 

      });
    },
    async confirmTiming() {
      this.storedTimer = this.hours * 3600 + this.minutes * 60 + this.seconds;
      this.timing = true;
      await storage.set("storedTimer", this.storedTimer.toString()+"_timer").then(() => {
        this.countdown(this.storedTimer);
      });
    },
    async sendStayFocedMessage() {
      await this.confirmTiming();
      console.log("send to stayfoced");
      const resp = await sendToBackground({
        name: "StayFoced",
        body: {
          message: "beginFoced",
          duration: this.storedTimer
        }
      });
    },
    countdown(t) {
      const remainingTime = t;
      if (remainingTime > 0) {
        this.storedTimer--;
        setTimeout(() => this.countdown(remainingTime - 1), 1000);
      } else {
        this.timing = false;
        this.timeUp = true;
      }
    },
    async resetTiming() {
      this.timing = false;
      this.timeUp = false;
    }
  }
};
</script>

<style>
.countdown-animation {
  display: flex;
  flex-direction: row;
}

.digit {
  font-size: 3em;
  margin: 0 5px;
}

.animation-active {
  animation: zoom 1s infinite;
}

@keyframes zoom {
  0% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.2);
  }

  100% {
    transform: scale(1);
  }
}
</style>